//
//  NetWorkManager.m
//  HdStore
//
//  Created by zhenqiu on 15/11/23.
//  Copyright (c) 2015年 zhenqiu. All rights reserved.
//

#import "NetWorkManager.h"
#import "RegiestDeviceNumber.h"
#import "AFHTTPSessionManager+RequestField.h"
#import "RequestTimeOutAction.h"

/***  AFNetWorking 响应格式设置*/
#define AFAcceptableContentTypes [NSSet setWithObjects:@"application/xml",@"application/json",@"text/json", @"text/plain", @"text/html", nil]



@interface NetWorkManager()

@end



@implementation NetWorkManager
@synthesize sessionManager;

+ (id) getInstance
{
    static dispatch_once_t  once;
    static id instance = nil;
    dispatch_once(&once, ^{
        
        instance = [[self  alloc] init];
        
    });
    
    return  instance;
}

-(instancetype) init
{
    self = [super init];
    if(self)
    {
        [self initSessionManager];
    }
    
    return self;
}

-(void)initSessionManager{
    NSURLSessionConfiguration * sessionConfigure = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfigure.timeoutIntervalForRequest = 5;
    sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HaoDai_URL] sessionConfiguration:sessionConfigure];
    AFHTTPRequestSerializer *test = [AFHTTPRequestSerializer serializer];
    
    NSString *oauth2 = @"oauth2 ";
    oauth2 = [oauth2 stringByAppendingString:OAUTH2];
    [test setValue:oauth2 forHTTPHeaderField:@"Authorization"];
    [sessionManager setRequestSerializer:test];
    [sessionManager setResponseSerializer:[AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments]];
    sessionManager.responseSerializer.acceptableContentTypes =AFAcceptableContentTypes;
}


-(void)requestWithUrl:(NSString *)url withParameters:(id)parameters withCompletion:(CompletionBlock)block{
    
    NSMutableDictionary* dic = [FSRequestAction genFSBaseParameter];
    if(parameters){
        [dic addEntriesFromDictionary:parameters];
    }
    [self requestWithUrl:url withParameters:dic withFormData:nil withCompletion:block  withType:POST_M];
}

-(void)requestWithUrl:(NSString *)url withParameters:(id)parameters withFormData:(NSData*)data withCompletion:(CompletionBlock)block{
    
    NSMutableDictionary* dic = [FSRequestAction genFSBaseParameter];
    if(parameters){
        [dic addEntriesFromDictionary:parameters];
    }

    [self requestWithUrl:url withParameters:dic withFormData:data withCompletion:block  withType:POST_MF];
}


-(void) requestWithUrl:(NSString *) urlStr withParameters:(id) parameters withFormData:(NSData*)data withCompletion:(CompletionBlock) block withType:(RequestType) type{
    
    NSString * urlf = [FSRequestAction createUrl:urlStr];
    
    switch (type) {
        
        case POST_M:
        
            [self postWithUrl:urlf withParameters:parameters withCompletion:block];
            break;
            
        case POST_MF:
            
            [self postWithUrl:urlf withParameters:parameters withFormData:data withCompletion:block];
            break;
        
        default:
        
        break;
    }
}


-(void)postWithUrl:(NSString*)url withParameters:(id) parameters withFormData:(NSData*)data withCompletion:(CompletionBlock) block{
    
    [self basePostWithUrl:url withParameters:parameters withFormBlock:^(id<AFMultipartFormData> formData) {
        
        if(data){
            
            NSString * name = [parameters valueForKey:@"file_name"];
            NSString * fileName = [NSString stringWithFormat:@"%@.jpeg",name];
            [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpeg"];
        }
        
    } withCompletion:block];
    
}

-(void) postWithUrl:(NSString *) url withParameters:(id) parameters withCompletion:(CompletionBlock) block
{
    [self basePostWithUrl:url withParameters:parameters withFormBlock:nil withCompletion:block];
}


-(void)basePostWithUrl:(NSString *) url withParameters:(id) parameters withFormBlock:(void (^)(id <AFMultipartFormData> formData)) formBlock withCompletion:(CompletionBlock) block{
  
  [sessionManager POST:url parameters:parameters constructingBodyWithBlock:formBlock withRequestFiled:^(NSMutableURLRequest *request) {
    
    [RequestTimeOutAction setRequestTimeout:request];
    
  } progress:nil success:^(NSURLSessionDataTask *task, id  _Nullable responseObject) {
    dispatch_async(dispatch_get_main_queue(), ^{
      
      NSError *error = nil;
      
      id data = [FSResponseAction parseReponseData:responseObject withError:&error];
      
      if (error) {
        
        NSError * ferror = [FSResponseAction getReponseError:error];
        
        if(block){
          
          block(data,ferror);
        }
        
        
      }else{
        
        if(block){
          
          block(data,nil);
        }
      }
      
    });
    
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
      
      NSError * ferror = [FSResponseAction getReponseError:error];
      
      if(block){
        
        block(nil,ferror);
      }
      
    });
    
  }];
  
}
/*
-(void)basePostWithUrl:(NSString *) url withParameters:(id) parameters withFormBlock:(void (^)(id <AFMultipartFormData> formData)) formBlock withCompletion:(CompletionBlock) block{
 
 
    [sessionManager POST:url parameters:parameters constructingBodyWithBlock:formBlock progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSError *error = nil;
            
            id data = [FSResponseAction parseReponseData:responseObject withError:&error];
            
            if (error) {
                
                NSError * ferror = [FSResponseAction getReponseError:error];
                
                if(block){
                    
                    block(data,ferror);
                }
                
                
            }else{
                
                if(block){
                    
                    block(data,nil);
                }
            }
            
        });

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSError * ferror = [FSResponseAction getReponseError:error];
            
            if(block){
                
                block(nil,ferror);
            }
            
        });

    }];
    
}*/



@end
